import { userInRoleInfoApi } from '@/apis/system'
import { loginAPI } from '@/apis/user'
import router from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { Message } from 'element-ui'

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    profile: []
  },
  mutations: {
    setUserTokenfn(state, token) {
      state.token = token
      setToken(token)
      Message.success('登录成功')
      if (router.app.$route.query.redirect) {
        router.push(router.app.$route.query.redirect)
        return
      }

      router.push('/')
    },
    logOut(state) {
      removeToken()
      state.token = ''
      Message.success('退出成功')
    },
    // 设置登录时的个人信息
    setProfile(state, res) {
      state.profile = res
    }
  },
  actions: {
    // 登录
    async doLogin(content, obj) {
      const res = await loginAPI(obj)
      content.commit('setUserTokenfn', res.data.token)
    },
    // 获取个人信息
    async getProfile(content) {
      const res = await userInRoleInfoApi()
      content.commit('setProfile', res.data)

      return res.data.permissions
    }
  }
}
